package br.com.der.almo.dao;

import br.com.der.almo.generica.Generica;
import br.com.der.almo.util.jpaUtil;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;




public abstract class JPAHibernateDAO <T extends Generica> {

	
	public abstract Class obterClasse();
	
	
	public void incluir(T t){
		EntityManager em = jpaUtil.getEntityManager();
		em.getTransaction().begin();
		em.persist(t);
		em.getTransaction().commit();
		em.close();
	}
	
	
	public void alterar(T t){
		EntityManager em = jpaUtil.getEntityManager();
		em.getTransaction().begin();
		em.merge(t);
		em.getTransaction().commit();
		em.close();
	}
	
	public void remover(T t){
		EntityManager em = jpaUtil.getEntityManager();
		em.getTransaction().begin();
		em.remove(t);
		em.getTransaction().commit();
		em.close();
	}
	
	public void remover2(T t){
		EntityManager em = jpaUtil.getEntityManager();
		em.getTransaction().begin();
		em.remove(em.getReference(t.getClass(), t.getIdentificador()));
		em.getTransaction().commit();
		em.close();
	}
	
	public List<T> listar(){
		EntityManager em = jpaUtil.getEntityManager();
		em.getTransaction().begin();
		String hql = "g from " + obterClasse().getSimpleName();
                
		List<T> lista = em.createQuery(hql).getResultList();
		return lista;
		
	}
	
	
//	public List<T> listar(){
//		EntityManager em = jpaUtil.getEntityManager();
//		em.getTransaction().begin();
//		String hql = "g from " + obterClasse().getCanonicalName();
//		List<T> lista = em.createQuery(hql).getResultList();
//		return lista;
//		
//	}
	
	public List<T> findAll() {
		EntityManager em = jpaUtil.getEntityManager();
                
        Query q = em.createQuery("select object(o) from "+obterClasse().getSimpleName()+" as o");
        return q.getResultList();
    }
	
        
        
        //metodo modificado para listar em uma jTable
        public ArrayList<T> findAll2() {
		EntityManager em = jpaUtil.getEntityManager();
                
        Query q = em.createQuery("select object(o) from "+obterClasse().getSimpleName()+" as o");
        return  (ArrayList<T>) q.getResultList();
    }
	
	public T consultar(T t){
		EntityManager em = jpaUtil.getEntityManager();
		t = (T)em.find(obterClasse(),t.getIdentificador());
		return t;
		
	}
	
	
	
	
	
	
	
}
